﻿using System.Collections.Specialized;
using System.Windows.Controls;
using System.Windows;
using Microsoft.Xaml.Behaviors;

namespace ChatClient.Tools.Behaviors
{
    public class BringNewItemIntoViewBehavior : Behavior<ItemsControl>
    {
        private INotifyCollectionChanged? _notifier;

        protected override void OnAttached()
        {
            base.OnAttached();

            _notifier = AssociatedObject.Items;
            if (_notifier != null)
            {
                _notifier.CollectionChanged += OnCollectionChanged;
            }
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            if (_notifier != null)
            {
                _notifier.CollectionChanged -= OnCollectionChanged;
            }
        }

        private void OnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action != NotifyCollectionChangedAction.Add)
            {
                return;
            }

            var newIndex = e.NewStartingIndex;
            var newElement = AssociatedObject.ItemContainerGenerator.ContainerFromIndex(newIndex);
            var item = (FrameworkElement)newElement;
            item.BringIntoView();
        }
    }
}
